package com.${sysEname}.controller;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.client.LogClient;
import com.apache.ius.common.CommonUtils;
import com.apache.ius.controller.BaseAction;
import com.apache.passport.common.DesUtils;
import com.apache.passport.entity.Token;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping({"/"})
public class IndexAction extends BaseAction {
    /**
    * 欢迎首页
    */
    @RequestMapping(value = "/", method = RequestMethod.GET)
        public String index(HttpServletRequest request) throws ServletException, IOException {
        return "/WEB-INF/pages/${sysEname}/admin/index";
    }

    /**
     * 管理端登录（/res/*配置在白名单内）
     */
    @RequestMapping(value = "/res/login", method = RequestMethod.POST)
    @ResponseBody
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("request url -->" + request.getRequestURI());
        ResultMsg msg = new ResultMsg("F", "登录失败");
        Map<String, String> params = this.getParameterMap(request);
        Map<String, Object> maps = new HashMap<String, Object>();
        String username = params.get("username");
        String password = params.get("password");

        //验证码判断
        msg = checkRandCode(request, params);
        if (null != msg) {
            gotoErrorPage(request, response, msg.getMsg());
            return;
        }

        //登录账号判断
        if (StrUtil.isNull(username) || StrUtil.isNull(password)) {
            msg = new ResultMsg("F", "用户名或密码不能为空");
            gotoErrorPage(request, response, msg.getMsg());
            return;
        }
        maps.put("userEname", username);
        maps.put("Client-IP", StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
        maps.put("userPass", password);
        maps.put("sysEname", ToolsUtil.getInstance().getValueByKey("sysEname"));
        maps.put("addressIP", maps.get("Client-IP"));
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("ssoService", "outSideSocketLoginService", maps,
                        PortalPubFactory.getInstance().getRpcInfo("sso"));
        //解析sso返回登录结果
        JSONObject resObj = new JSONObject();
        if (entity != null && ("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof String) {
                String userMsg = String.valueOf(entity.getMessage());
                log.error("登录提示：" + userMsg);

                if (userMsg.indexOf("用户已停用") > -1) {
                    msg = new ResultMsg("F", "您的账户正在审核，请耐心等待！");
                } else if (userMsg.indexOf("删除") > -1) {
                    msg = new ResultMsg("F", "您的账户已关闭登录操作，请联系管理人员！");
                } else {
                    if ("密码错误".equals(userMsg) || "用户不存在".equals(userMsg)) {
                        msg = new ResultMsg("F", "用户登录信息有误");
                    } else {
                        msg = new ResultMsg("F", userMsg);
                    }
                }
                resObj = JSONObject.fromObject(msg);
            } else {
                //仓储cookie
                Token token = (Token) entity.getEntity();
                Cookie cookie = new Cookie(ToolsUtil.getInstance().getValueByKey("cookieName"),
                        token.getTokenId());
                cookie.setPath("/");
                cookie.setMaxAge(-1);
                Cookie ucsso = new Cookie("_uc.sso",
                        DesUtils.getInstance().decrypt(token.getUserEname()));
                ucsso.setPath("/");
                ucsso.setMaxAge(-1);
                request.getSession().removeAttribute("loginUser");
                request.getSession().removeAttribute("tokenId");

                msg = new ResultMsg("T", "登录成功");

                //剔除loginInfo，解密email，userEname，mobile传明文
                JsonConfig jc = new JsonConfig();
                String config[] = {"loginInfo"};
                jc.setExcludes(config);
                String token_email = token.getEmail();
                String token_mobile = token.getMobile();
                String token_userEname = token.getUserEname();
                token.setEmail(DesUtils.getInstance().decrypt(token_email));
                token.setMobile(DesUtils.getInstance().decrypt(token_mobile));
                token.setUserEname(DesUtils.getInstance().decrypt(token_userEname));
//                msg = new ResultMsg("T", JSONObject.fromObject(token, jc).toString());
                resObj = JSONObject.fromObject(msg, jc);
                //存储session
                if ("T".equals(msg.getFlag())) {
                    JSONObject jb = JSONObject.fromObject(token);
                    Map<String, Object> map = (Map) jb;
                    LoginUser loginUser = PBOSSOTools.getLoginUserFromUserCenter(String.valueOf(map.get("userEname")),
                            String.valueOf(map.get("tokenId")));
                    if (loginUser != null) {
                        jb.put("sysFlag", loginUser.getSysFlag());
                        User user = loginUser.getUser();
                        if (user != null) {
                            Integer userSore = user.getUserScore();
                            if ((!"manager".equals(token.getUserType()) && !"0".equals(token.getUserType())) && 10 != userSore) {
                                msg = new ResultMsg("F", "此账号暂无权限登录");
                                gotoErrorPage(request, response, msg.getMsg());
                                return;
                            }
                            jb.put("auditStatus", StrUtil.doNull(user.getAuditStatus(), ""));
                            jb.put("appId", StrUtil.doNull(user.getAppUid(), ""));
                            jb.put("userScore", userSore);
                        }
                    }
                    resObj.put("loginUser", jb);

                    response.addCookie(cookie);
                    response.addCookie(ucsso);
                    request.getSession().setAttribute("tokenId", token.getTokenId());
                    request.getSession().setAttribute("loginUser", loginUser);
                }
                log.info("[" + username + "]登录成功！");

                //记录日志
                Map<String, Object> logMap = new HashMap<String, Object>();
                logMap.put("logOperationType", "login");
                logMap.put("logClassName", User.class.getName());
                logMap.put("logIp", maps.get("Client-IP"));
                logMap.put("log_userEname", token.getUserEname());
                log.info("登录成功日志：" + logMap);
                LogClient.getInstance().execute(logMap);//添加日志

            }
        }
        log.info("[" + username + "]登录结果：" + msg.toString());
        this.outputJson(resObj.toString(), response, "");
    }

    /**
     * description:  验证验证码
     */
    private ResultMsg checkRandCode(HttpServletRequest request, Map<String, String> params) {
        String if_randCode = StrUtil.doNull(CommonUtils.getConfigVal("if_randCode"), "T");
        if ("F".equals(if_randCode)) {
            return null;
        }
        ResultMsg msg = null;
        String session_randCode = String.valueOf(request.getSession().getAttribute("randCode"));
        if (ToolsUtil.isNull(session_randCode))
            return null;
        if ((StrUtil.isNull(params.get("rand")))) {
            msg = new ResultMsg("F", "验证码不能为空");
            return msg;
        }
        if (!params.get("rand").equals(session_randCode)) {
            msg = new ResultMsg("F", "验证码错误");
            return msg;
        }
        return msg;
    }
}

